package com.jiyinit.web.core.activiti.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.activiti.dto.TabUserMemershipRequest;
import com.jiyinit.web.core.activiti.entity.TabUserMemershipEntity;
import com.jiyinit.web.core.activiti.service.UserMemershipServiceImpl;
import com.jiyinit.web.core.business.entity.TabCoreDictItemEntity;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.DictItemServiceImpl;
import com.jiyinit.web.core.business.service.OrgServiceImpl;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author liuzongguang
 * @date 2018/7/24.
 */
@Controller
@RequestMapping(value = "/userMemerShip")
public class UserMemerShipController {
    /**
     * 日志对象
     */
    private final static Logger LOGGER = LoggerFactory.getLogger(DataStatisticsController.class);

    @Resource(name = "userMemershipServiceImpl")
    UserMemershipServiceImpl userMemershipService;

    @Resource(name = "core.dictItemServiceImpl")
    DictItemServiceImpl dictItemService;

    @RequestMapping(value="/toUserMemerShip", method = RequestMethod.GET)
    public String toUserMemerShip() {
        return "/usermemership/list";
    }

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    @Resource(name = "core.orgServiceImpl")
    private OrgServiceImpl orgService;

     /**
      * 获取用户关系组数据列表
      * @author liuzongguang
      * @create 2018/7/24 9:35
      * @param
      * @return
      */

    @RequestMapping(method = RequestMethod.POST, value = "/getListForPage")
    @ResponseBody
    public PagingResult getListForPage(TabUserMemershipRequest request){
        PagingResult<TabUserMemershipRequest> pagingResult = userMemershipService.getListForPage(request);
        LogUtil.info(LOGGER,"pagingResult:{}", JsonEntityTransform.object2Json(pagingResult));
        return pagingResult;
    }

     /**
      * 添加页面
      * @author liuzongguang
      * @create 2018/7/24 9:47
      * @param
      * @return
      */
    @RequestMapping(value = "/userMemerShipAdd")
    public String toRoleAdd(HttpServletRequest request, Integer parentId) {
        return "/usermemership/add";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/getFlowNodesById")
    @ResponseBody
    public ResponseEntity<ResponseDto> getFlowNodesById(TabUserMemershipRequest request){
        List<TabCoreDictItemEntity> list=dictItemService.selectByDictCode(request.getProcinstKey());
        return new ResponseEntity<>(ResponseDto.responseOK(list), HttpStatus.OK);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/save")
    public ResponseEntity<ResponseDto> save(HttpServletRequest request, TabUserMemershipEntity userMemershipEntity) {
        // 校验参数
        ValidateResult<TabUserMemershipEntity> validateResult = paramCheckLogic.checkParamValidate(userMemershipEntity);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }

        userMemershipEntity.setIsDelete("0");

        //校验添加内容是否重复，不用判断部门和是否主要审批人
        TabUserMemershipEntity validEntity=new TabUserMemershipEntity();
        BeanUtils.copyProperties(userMemershipEntity, validEntity);
        validEntity.setOrgId(null);
        validEntity.setIsMain(null);
        List<TabUserMemershipEntity> findList=userMemershipService.findBySelective(validEntity);
        if(findList!=null&&findList.size()>0)
        {
            return new ResponseEntity<>(ResponseDto.responseFail("保存失败,不能重复添加记录"), HttpStatus.OK);
        }

        int num = userMemershipService.insert(userMemershipEntity);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK("保存成功"), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("保存失败"), HttpStatus.OK);
    }

    /**
     * 修改数据
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/modify")
    public ResponseEntity<ResponseDto> modify(HttpServletRequest request, TabUserMemershipEntity userMemershipEntity) {
        // 校验参数
        ValidateResult<TabUserMemershipEntity> validateResult = paramCheckLogic.checkParamValidate(userMemershipEntity);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }

        //校验添加内容是否重复，不用判断部门和是否主要审批人
        TabUserMemershipEntity validEntity=new TabUserMemershipEntity();
        BeanUtils.copyProperties(userMemershipEntity, validEntity);
        validEntity.setOrgId(null);
        validEntity.setIsMain(null);
        List<TabUserMemershipEntity> findList=userMemershipService.findBySelective(validEntity);
        if(findList!=null&&findList.size()>0)
        {
            //findList不是当前修改的数据，说明修改数据和其它数据重复
            if(findList.get(0).getId()!=userMemershipEntity.getId())
            {
                return new ResponseEntity<>(ResponseDto.responseFail("保存失败,不能重复添加记录"), HttpStatus.OK);
            }
        }

        userMemershipEntity.setIsDelete("0");
        int num = userMemershipService.updateByPrimaryKey(userMemershipEntity);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK("保存成功"), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("保存失败"), HttpStatus.OK);
    }

    /**
     * 跳到修改页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(Model model,HttpServletRequest request,Integer id) {
        TabUserMemershipEntity userMemership=userMemershipService.selectByPrimaryKey(id);
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userMemership.getUserId());
        TabCoreOrgEntity coreOrg = orgService.selectById(userMemership.getOrgId());

        TabUserMemershipRequest tabUserMemershipRequest=new TabUserMemershipRequest();
        BeanUtils.copyProperties(userMemership, tabUserMemershipRequest);
        if(coreOrg!=null)
        {
            tabUserMemershipRequest.setOrgName(coreOrg.getOrgName());
        }
        if(coreUser!=null)
        {
            tabUserMemershipRequest.setUserName(coreUser.getUserName());
        }
        model.addAttribute("userMemership",tabUserMemershipRequest);
        return "/usermemership/edit";
    }

     /**
      * 数据删除
      * @author liuzongguang
      * @create 2018/7/25 11:27
      * @param
      * @return
      */
    @RequestMapping(method = RequestMethod.POST, value = "/delete")
    @ResponseBody
    public ResponseEntity<ResponseDto> delete(Integer[] ids) {
        int num=userMemershipService.deleteByIds(ids);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK("操作成功"), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("操作失败"), HttpStatus.OK);
    }
}
